<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="项目名称" prop="projectId">
          <el-select
            v-model="queryParams.projectId"
            placeholder="项目名称"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in projectsList"
              :key="dict.id"
              :label="dict.projectName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
       <el-form-item label="所属公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="所属公司"
          clearable
          style="width: 240px"
          @change="handleCompanyChange"
        >
          <el-option
            v-for="dict in companiesList"
            :key="dict.id"
            :label="dict.companyName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="门窗类型" prop="companyId">
        <el-select
          v-model="queryParams.typeId"
          placeholder="门窗类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in typesList"
            :key="dict.id"
            :label="dict.typeName"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['material-cutting-plan:windows:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['material-cutting-plan:windows:edit']"
        >修改</el-button> -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['material-cutting-plan:windows:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportByIds"
        >导出下料单</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="windowsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <!-- <el-table-column label="所属项目ID" align="center" prop="projectId" />
      <el-table-column label="门窗类型ID" align="center" prop="typeId" /> -->
      <!-- <el-table-column label="门窗名称" align="center" prop="windowsName" /> -->
      <el-table-column label="门窗名称" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
           <el-button
            size="mini"
            type="text"
          @click="getListResults(scope.row.id)"
          >{{scope.row.windowsName}}</el-button>

        </template>
      </el-table-column>
      <el-table-column label="所属项目" align="center" prop="projectName" />
      <el-table-column label="门窗类型" align="center" prop="typeName" />
      <el-table-column label="门窗类型图片路径" align="center" prop="typeImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.typeImage" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="门窗宽度(单位:mm)" align="center" prop="width" />
      <el-table-column label="门窗高度(单位:mm)" align="center" prop="height" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="备注信息" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['material-cutting-plan:windows:edit']"
          >修改</el-button>
          -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh"
            @click="handleCalculate(scope.row)"
          >计算下料单</el-button>
           <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
          @click="getListResults(scope.row.id)"
          >查看下料单</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['material-cutting-plan:windows:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改门窗详细信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="门窗名称" prop="windowsName">
          <el-input v-model="form.windowsName" placeholder="请输入门窗名称" maxlength="20"/>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectId">
          <el-select
            v-model="form.projectId"
            placeholder="项目名称"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in projectsList"
              :key="dict.id"
              :label="dict.projectName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
       <el-form-item label="所属公司" prop="companyId">
          <el-select
            v-model="form.companyId"
            placeholder="所属公司"
            clearable
            style="width: 240px"
            @change="handleCompanyChange_update"
          >
            <el-option
              v-for="dict in companiesList"
              :key="dict.id"
              :label="dict.companyName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="门窗类型" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="门窗类型"
            clearable
            style="width: 240px"
            @change="handleTypesChange_update"
          >
            <el-option
              v-for="dict in typesListUpdate"
              :key="dict.id"
              :label="dict.typeName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      <el-form-item label="类型图片" prop="typeImage" width="100">
        <image-preview :src="form.typeImage" :width="50" :height="50"/>
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
      </el-form-item>
        <el-form-item label="门窗宽度(单位:mm)" prop="width">
          <el-input v-model="form.width" placeholder="请输入门窗宽度(单位:mm)" />
        </el-form-item>
        <el-form-item label="门窗高度(单位:mm)" prop="height">
          <el-input v-model="form.height" placeholder="请输入门窗高度(单位:mm)" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 计算门窗详细信息对话框 -->
    <el-dialog :title="title" :visible.sync="openCalculate" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="门窗名称" prop="windowsName">
            <el-input v-model="form.windowsName" placeholder="请输入门窗名称" maxlength="20"/>
          </el-form-item>
          <el-form-item label="项目名称" prop="projectId">
            <el-select
              v-model="form.projectId"
              placeholder="项目名称"
              clearable
              style="width: 240px"
            >
            <el-option
              v-for="dict in projectsList"
              :key="dict.id"
              :label="dict.projectName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
       <el-form-item label="所属公司" prop="companyId">
          <el-select
            v-model="form.companyId"
            placeholder="所属公司"
            clearable
            style="width: 240px"
            @change="handleCompanyChange_update"
          >
            <el-option
              v-for="dict in companiesList"
              :key="dict.id"
              :label="dict.companyName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="门窗类型" prop="typeId">
          <el-select
            v-model="form.typeId"
            placeholder="门窗类型"
            clearable
            style="width: 240px"
            @change="handleTypesChange_update"
          >
            <el-option
              v-for="dict in typesListUpdate"
              :key="dict.id"
              :label="dict.typeName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
      <el-form-item label="类型图片" prop="typeImage" width="100">
        <image-preview :src="form.typeImage" :width="50" :height="50"/>
      </el-form-item>
      <el-form-item label="备注信息" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" maxlength="100"/>
      </el-form-item>
        <el-form-item label="门窗宽度(单位:mm)" prop="width">
          <el-input v-model="form.width" placeholder="请输入门窗宽度(单位:mm)" maxlength="6"  @input="handleWindowSizeChange($event,'w')"/>
        </el-form-item>
        <el-form-item label="门窗高度(单位:mm)" prop="height">
          <el-input v-model="form.height" placeholder="请输入门窗高度(单位:mm)" maxlength="6" @input="handleWindowSizeChange($event,'h')"/>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" maxlength="6"/>
        </el-form-item>
        <el-divider content-position="center">门窗用料公式值信息</el-divider>
        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddMcpVariableValue">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteMcpVariableValue">删除</el-button>
          </el-col>
        </el-row> -->
        <el-table :data="mcpVariableValueList" :row-class-name="rowMcpVariableValueIndex" @selection-change="handleMcpVariableValueSelectionChange" ref="mcpVariableValue">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <!-- <el-table-column label="变量ID" prop="variableId" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.variableId" placeholder="请输入变量ID" />
            </template>
          </el-table-column> -->
          <el-table-column label="变量" prop="variableName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.variableName" placeholder="变量" readonly="readonly" />
            </template>
          </el-table-column>
          <el-table-column label="赋值" prop="value" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.value" placeholder="请输入赋值" maxlength="6" @input="handleVariableValueChange($event,scope.row.variableName)" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormCalculate">确 定</el-button>
        <el-button @click="cancelCalculate">取 消</el-button>
      </div>
    </el-dialog>

     <!-- 门窗信息对话框 -->
    <el-dialog title="下料单" :visible.sync="openCalculateResults" width="500px" append-to-body>
      <el-table v-loading="loading" :data="resultsList">
        <el-table-column label="材料名称" align="center" prop="materialName" />
        <el-table-column label="材料长度(单位:mm)" align="center" prop="materialLength" />
        <el-table-column label="材料数量" align="center" prop="materialCount" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitFormCalculate">确 定</el-button>
        <el-button @click="cancelCalculate">取 消</el-button> -->
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExportById"
          v-hasPermi="['material-cutting-plan:windows:export']"
        >导出下料单</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listWindows, getWindows, delWindows, addWindows, updateWindows, calculate } from "@/api/material-cutting-plan/windows"
import { listTypes } from "@/api/material-cutting-plan/types"
import { listCompanies } from "@/api/material-cutting-plan/companies"
import { listProjects } from "@/api/material-cutting-plan/projects"
import { listResults } from "@/api/material-cutting-plan/results"

export default {
  name: "Windows",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedMcpVariableValue: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门窗详细信息表格数据
      windowsList: [],
      // 门窗用料公式值表格数据
      mcpVariableValueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详细对话框
      openCalculate: false,
      // 是否显示计算结果对话框
      openCalculateResults: false,

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        typeId: null,
        width: null,
        height: null,
        quantity: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        windowsName: [
          { required: true, message: "门窗名称不能为空", trigger: "change" },
          { max: 20, message: '长度不能多于20个字符', trigger: 'blur' }
        ],
        projectId: [
          { required: true, message: "所属项目不能为空", trigger: "change" }
        ],
        companyId: [
          { required: true, message: "所属公司不能为空", trigger: "change" }
        ],
        typeId: [
          { required: true, message: "门窗类型不能为空", trigger: "change" }
        ],
        width: [
          { required: true, message: "门窗宽度(单位:mm)不能为空", trigger: "blur" }
        ],
        height: [
          { required: true, message: "门窗高度(单位:mm)不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
      },
      // 门窗用料公式值表单参数
      mcpVariableValueForm: {},
      // 门窗用料公式值表单校验
      mcpVariableValueRules: {
        variableId: [
          { required: true, message: "变量不能为空", trigger: "change" }
        ],
        value: [
          { required: true, message: "值不能为空", trigger: "blur" }
        ],
      },
    typesList: [],
    typesListUpdate:[],
    companiesList: [],
    projectsList: [],
    resultsList: [],
    exportId: null,

    }
  },
  created() {
    if(this.$route.query.projectId != null){
        this.queryParams.projectId = Number(this.$route.query.projectId)
      }
    this.getList()
    this.getListCompanies()
    this.getListProjects()
  },
  watch: {
    // 根据名称筛选
    $route: function (to,from) {
      if(to.name!='Windows'){
        return;
      }
      if(this.$route.query.projectId != null){
        this.queryParams.projectId = Number(this.$route.query.projectId)
      }
      this.getList()
      this.getListCompanies()
      this.handleRouteChange()
    }
  },
  methods: {
    /** 查询门窗详细信息列表 */
    getList() {
      this.loading = true
      listWindows(this.queryParams).then(response => {
        this.windowsList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询工程项目信息列表 */
    getListProjects() {
      listProjects({pageSize:9999}).then(response => {
        this.projectsList = response.rows
      })
    },
    /** 查询门窗用料计算结果列表 */
    getListResults(windowId) {
      this.exportId = windowId;
      listResults({"windowId":windowId,"pageSize":9999}).then(response => {
        this.resultsList = response.rows
        this.openCalculateResults = true
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        typeId: null,
        width: null,
        height: null,
        quantity: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.mcpVariableValueList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    getListCompanies() {
      listCompanies({pageSize:9999}).then(response => {
        this.companiesList = response.rows
      })
    },
    handleCompanyChange(value){
      this.typesList =[];
      this.queryParams.typeId = null;
      listTypes({companyId: value,pageSize:9999}).then(response => {
        this.typesList = response.rows
      })
    },
    handleCompanyChange_update(value){
      this.typesListUpdate =[];
      this.form.typeId = null;
      this.form.typeImage = null;
      if (value == null){
        return
      }
       listTypes({companyId: value,pageSize:9999}).then(response => {
        this.typesListUpdate = response.rows
      })
    },
     handleTypesChange_update(value){
      for (let index = 0; index < this.typesListUpdate.length; index++) {
        const element = this.typesListUpdate[index];
        if(element.id == value) {
          this.form.typeImage = element.typeImage;
        }
      }
    },

    handleTypeImageChange(value) {
      for (let index = 0; index < this.typesListUpdate.length; index++) {
        const element = typesListUpdate[index];
        if(element.id == value) {
          this.form.typeImage = element.typeImage;
        }

      }
      form.typeImage = value;
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加门窗详细信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getWindows(id).then(response => {
        this.form = response.data
        this.mcpVariableValueList = response.data.mcpVariableValueList
        this.open = true
        this.title = "修改门窗详细信息"
        listTypes({companyId: this.form.companyId}).then(response => {
          this.typesListUpdate = response.rows
        })
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.mcpVariableValueList = this.mcpVariableValueList
          if (this.form.id != null) {
            updateWindows(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addWindows(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除门窗详细信息编号为"' + ids + '"的数据项？').then(function() {
        return delWindows(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 门窗用料公式值序号 */
    rowMcpVariableValueIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 门窗用料公式值添加按钮操作 */
    handleAddMcpVariableValue() {
      let obj = {}
      obj.variableId = ""
      obj.value = ""
      obj.remark = ""
      this.mcpVariableValueList.push(obj)
    },
    /** 门窗用料公式值删除按钮操作 */
    handleDeleteMcpVariableValue() {
      if (this.checkedMcpVariableValue.length == 0) {
        this.$modal.msgError("请先选择要删除的门窗用料公式值数据")
      } else {
        const mcpVariableValueList = this.mcpVariableValueList
        const checkedMcpVariableValue = this.checkedMcpVariableValue
        this.mcpVariableValueList = mcpVariableValueList.filter(function(item) {
          return checkedMcpVariableValue.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleMcpVariableValueSelectionChange(selection) {
      this.checkedMcpVariableValue = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('material-cutting-plan/windows/export', {
        ...this.queryParams
      }, `windows_${new Date().getTime()}.xlsx`)
    },
    handleExportByIds(){
      this.download('material-cutting-plan/windows/exportByIds', {
        ids: this.ids.join(",")
      }, `windows_${new Date().getTime()}.xlsx`)
    },
    handleExportById(){
      this.download('material-cutting-plan/windows/exportByIds', {
        ids: this.exportId
      }, `windows_${new Date().getTime()}.xlsx`)
    },
    handleCalculate(row) {
      this.reset()
      const id = row.id || this.ids
      getWindows(id).then(response => {
        this.form = response.data

        this.form.mcpVariableValueList.forEach((item, index) => {
          if (item.variableName != null && item.variableName.toLowerCase() === 'h') {
            item.value = row.height
          }
          if (item.variableName != null && item.variableName.toLowerCase() === 'w') {
            item.value = row.width
          }
        })

        this.mcpVariableValueList = this.form.mcpVariableValueList
        this.openCalculate = true
        this.title = "计算门窗详细信息"



        if (this.mcpVariableValueList != null && this.mcpVariableValueList.length > 0){
          this.mcpVariableValueList.forEach(element => {
            if (element.variableName != null && element.value ==null && element.variableName.toUpperCase()=="H"){
              element.value = this.form.height;
            }else if (element.variableName != null && element.value ==null && element.variableName.toUpperCase()=="W"){
              element.value = this.form.width;
            }
          });
        }
        listTypes({companyId: this.form.companyId,pageSize:9999}).then(response => {
          this.typesListUpdate = response.rows
        })
      })
    },
    // 计算下料单
    submitFormCalculate() {
      updateWindows(this.form).then(response => {
        this.openCalculate = false
        console.log(response)
        calculate(this.form.id).then(response => {
          console.log(response)
          this.getListResults(this.form.id)
        })
      })
    },
  handleWindowSizeChange(value,name) {
    this.form.mcpVariableValueList.forEach((item, index) => {
          if (item.variableName != null && item.variableName.toLowerCase() === name) {
            item.value = value
          }
        })
  },
  handleVariableValueChange(value,name) {
    console.log(value)
    if (name.toLowerCase() === 'h') {
      this.form.height= value
    } else if (name.toLowerCase() === 'w') {
      this.form.width= value
    }
  },


    // handleCalculate(row) {

    //   updateWindows(this.form).then(response => {
    //     this.openCalculate = false
    //     this.calculate(this.form.id).then(response => {
    //       getWindows(this.form.id).then(response => {
    //         this.form = response.data
    //         this.mcpVariableValueList = response.data.mcpVariableValueList
    //         this.openCalculate = true
    //         this.title = "计算门窗详细信息"
    //       })
    //     })
    //   })
    // },

    // 取消按钮
    cancelCalculate() {
      this.openCalculate = false
      this.reset()
    },
  }
}
</script>
